﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Novel.Server.Models;
using Novel.Server.Response;
using System.Security.Claims;
using System.Linq;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Novel.Server.Controllers
{
    /// <summary>
    /// 负责评论相关操作
    /// </summary>
    [Route("api/comment")]
    [ApiController]
    public class CommentController : ControllerBase
    {
        private readonly NovelContext dbContext;
        private readonly IConfiguration conf;

        public CommentController(NovelContext context, IConfiguration configuration)
        {
            dbContext = context;
            conf = configuration;
        }

        /// <summary>
        /// 发表评论
        /// </summary>
        [HttpPost("create")]
        [Authorize]
        public async Task<IActionResult> CreateComment([FromBody] CommentCreateDto dto)
        {
            var username = User.Identity?.Name;
            if (string.IsNullOrEmpty(username))
            {
                return Unauthorized(ApiResponse.ErrorResponse("用户未登录", 401));
            }
            
            var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == username);
            if (user == null || user.IsDeleted)
            {
                return BadRequest(ApiResponse.ErrorResponse("用户不存在", 400));
            }

            var chapter = await dbContext.Chapters.FirstOrDefaultAsync(c => c.ChapterId == dto.Cid);
            if (chapter == null || chapter.IsDeleted)
            {
                return BadRequest(ApiResponse.ErrorResponse("章节不存在或已被删除", 400));
            }

            var comment = new Comment
            {
                AuthorId = user.UserId,
                ChapterId = dto.Cid,
                Content = dto.Content,
                CreatedAt = DateTime.Now,
                IsDeleted = false
            };
            
            dbContext.Comments.Add(comment);
            await dbContext.SaveChangesAsync();

            return Ok(ApiResponse.SuccessResponse(new
            {
                id = comment.CommentId,
            }));
        }

        /// <summary>
        /// 获取评论列表（分页）
        /// </summary>
        [HttpGet("{chapterId}")]
        public async Task<IActionResult> GetCommentsByChapterId(int chapterId, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            var chapter = await dbContext.Chapters
                .Where(c => c.ChapterId == chapterId && !c.IsDeleted)
                .Include(c => c.Novel)
                .FirstAsync();

            if (chapter == null || chapter.IsDeleted)
            {
                return NotFound(ApiResponse.ErrorResponse("章节不存在或已被删除", 404));
            }

            var comments = dbContext.Comments
                .Where(c => c.ChapterId == chapterId && !c.IsDeleted)
                .Include(c => c.Author)
                .OrderByDescending(c => c.CreatedAt);

            var totalComments = await comments.CountAsync();
            var pagedComments = await comments
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            var result = pagedComments.Select(c => new
            {
                id = c.CommentId,
                author = new
                {
                    id = c.AuthorId,
                    name = c.Author.Username,
                    avatar = c.Author.Avatar,
                    role = c.Author.Role,
                },
                chapter = new
                {
                    id = c.ChapterId,
                    title = chapter.Title,
                },
                novel = new
                {
                    id = chapter.Novel.NovelId,
                    title = chapter.Novel.Title,
                },
                content = c.Content,
                created_at = c.CreatedAt
            });

            return Ok(ApiResponse.SuccessResponse(new
            {
                total = totalComments,
                comments = result
            }));
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        public async Task<IActionResult> DeleteComment(int id)
        {
            var comment = await dbContext.Comments
                .Include(c => c.Author)
                .Include(c => c.Chapter)
                .ThenInclude(c => c.Novel)
                .ThenInclude(c => c.Author)
                .FirstOrDefaultAsync(c => c.CommentId == id);
            if (comment == null)
            {
                return NotFound(ApiResponse.ErrorResponse("评论不存在", 404));
            }
            var username = User.Identity?.Name;
            if (string.IsNullOrEmpty(username))
            {
                return Unauthorized(ApiResponse.ErrorResponse("用户未登录", 401));
            }
            var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == username);
            if (user == null || user.IsDeleted)
            {
                return BadRequest(ApiResponse.ErrorResponse("用户不存在", 400));
            }

            var chapter = await dbContext.Chapters.FirstOrDefaultAsync(c => c.ChapterId == comment.ChapterId);
            var novel = await dbContext.Novels.FirstOrDefaultAsync(n => n.NovelId == chapter.NovelId);
            var novelAuthor = await dbContext.Users.FirstOrDefaultAsync(u => u.UserId == novel.AuthorId);

            var isAdmin = user.Role == "admin";
            var isMod = user.Role == "mod";
            var isCommentAuthor = comment.Author.Username == username;
            var isNovelAuthor = comment.Chapter.Novel.Author.Username == username;

            // 其他情况保持不变
            if (!isCommentAuthor && !isAdmin && !isMod && !isNovelAuthor)
            {
                return BadRequest(ApiResponse.ErrorResponse("您没有权限删除这条评论", 403));
            }

            comment.IsDeleted = true;
            dbContext.Comments.Update(comment);
            await dbContext.SaveChangesAsync();

            return Ok(ApiResponse.SuccessResponse(true));
        }

        /// <summary>
        /// 保存评论
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        public async Task<IActionResult> SaveComment(int id, [FromBody] CommentSaveDto dto)
        {
            var comment = await dbContext.Comments.FirstOrDefaultAsync(c => c.CommentId == id);
            if (comment == null || comment.IsDeleted)
                return NotFound(ApiResponse.ErrorResponse("评论不存在", 404));

            var username = User.Identity.Name;
            var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Username == username);
            if (user == null || user.IsDeleted)
                return BadRequest(ApiResponse.ErrorResponse("用户不存在", 400));

            var chapter = await dbContext.Chapters.FirstOrDefaultAsync(c => c.ChapterId == comment.ChapterId);
            var novel = await dbContext.Novels.FirstOrDefaultAsync(n => n.NovelId == chapter.NovelId);
            var novelAuthor = await dbContext.Users.FirstOrDefaultAsync(u => u.UserId == novel.AuthorId);

            var isCommentAuthor = comment.AuthorId == user.UserId;
            var isAdminOrMod = user.Role == "admin" || user.Role == "mod";
            var isNovelAuthor = novelAuthor.Username == username;

            if (!isCommentAuthor && !isAdminOrMod && !isNovelAuthor)
                return BadRequest(ApiResponse.ErrorResponse("您没有权限修改这条评论", 403));

            comment.Content = dto.Content;
            comment.CreatedAt = DateTime.Now;
            dbContext.Comments.Update(comment);
            await dbContext.SaveChangesAsync();

            return Ok(ApiResponse.SuccessResponse(new
            {
                id = comment.CommentId,
                created_at = comment.CreatedAt
            }));
        }

        /// <summary>
        /// 搜索评论（仅管理员和版主可用）
        /// </summary>
        [HttpGet("search")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> SearchComments([FromQuery] string keyword, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            var comments = dbContext.Comments
                .Where(c => !c.IsDeleted && EF.Functions.FreeText(c.Content, keyword))
                .Include(c => c.Author)
                .Include(c => c.Chapter)
                .ThenInclude(c => c.Novel)
                .OrderByDescending(c => c.CreatedAt);

            var totalComments = await comments.CountAsync();
            var pagedComments = await comments
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            var result = pagedComments.Select(c => new
            {
                id = c.CommentId,
                author = new 
                {
                    id = c.AuthorId,
                    name = c.Author.Username,
                    avatar = c.Author.Avatar,
                    role = c.Author.Role,
                },
                chapter = new
                {
                    id = c.ChapterId,
                    title = c.Chapter.Title,
                },
                novel = new
                {
                    id = c.Chapter.Novel.NovelId,
                    title = c.Chapter.Novel.Title,
                },
                content = c.Content,
                created_at = c.CreatedAt,
            });

            return Ok(ApiResponse.SuccessResponse(new
            {
                total = totalComments,
                comments = result
            }));
        }
    }

    public class CommentSaveDto
    {
        public required string Content { get; set; }
    }

    public class CommentCreateDto
    {
        public int Cid { get; set; }
        public required string Content { get; set; }
    }
}